'use client';
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { PlusIcon, XMarkIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
// 通过API Routes上传文件
export function UploadMirror({ slug }: { slug: string[] }) {
    const router = useRouter();

    const [visible, setVisible] = useState<boolean>(false);
    const [files, setFiles] = useState<FileList | null>(null);
    const [loading, setLoading] = useState<boolean>(false);

    const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        // 阻止表单提交行为
        e.preventDefault();
        if (!files) return;

        try {
            setLoading(true);
            const formData = new FormData();
            Array.from(files).forEach((file: File) => {
                formData.append('files', file);
            });
            const res = await fetch(`/api/upload/${slug.join('/')}`, {
                method: 'POST',
                body: formData,
            });
            // handle the error
            if (!res.ok) throw new Error(await res.text());
            setVisible(false);
            setLoading(false);
            setFiles(null);
            router.refresh();
        } catch (e) {
            // Handle errors here
            console.error(e);
        }
    };

    return (
        <div className='p-4'>
            <button
                onClick={() => {
                    setVisible(true);
                }}
                className='inline-flex items-center px-4 py-2 font-semibold leading-6 text-sm shadow rounded-md text-white bg-indigo-500 hover:bg-indigo-400 transition ease-in-out duration-150 '
            >
                <PlusIcon className='h-5' />
                <span className='hidden md:block'>上传文件</span>
            </button>
            {visible && (
                <div className='modal-root'>
                    <div className='modal-mask bg-opacity-50  bg-gray-400  fixed inset-0 z-[1000]   '>
                        <div className='modal-wrap fixed inset-0 z-[1000] overflow-auto outline-0'>
                            <div className='modal w-[520px] relative top-[100px] box-border my-0 mx-auto'>
                                <div>
                                    <div className='modal-content relative bg-white rounded-md shadow-md px-5 py-6'>
                                        <button
                                            onClick={() => {
                                                setVisible(false);
                                            }}
                                            className='modal-close absolute top-3 right-3 z-[1010]'
                                            type='button'
                                            title='删除'
                                        >
                                            <XMarkIcon className='w-8' />
                                        </button>
                                        <div className='modal-header mb-2 text-left'>
                                            <div className='modal-title'>
                                                上传文件到
                                                {slug.join('/')}
                                                /目录下
                                            </div>
                                        </div>
                                        <div className='modal-body'>
                                            <form
                                                className='flex flex-col'
                                                onSubmit={onSubmit}
                                            >
                                                <button
                                                    className={clsx('w-24 relative inline-flex items-center px-4 py-2 font-semibold leading-6 text-sm shadow rounded-md text-white bg-indigo-500 hover:bg-indigo-400 transition ease-in-out duration-150 ', {
                                                        'cursor-not-allowed': loading,
                                                    })}
                                                    disabled={loading}
                                                >
                                                    <input
                                                        multiple
                                                        type='file'
                                                        name='file'
                                                        className='absolute inset-0 opacity-0'
                                                        onChange={(e) => setFiles(e.target.files)}
                                                        title='选择文件'
                                                    />
                                                    <span>选择文件</span>
                                                </button>
                                                <ul className='text-left my-2'>
                                                    {files &&
                                                        Array.from(files).map((file: File) => {
                                                            return <li key={file.name}>{file.name}</li>;
                                                        })}
                                                </ul>
                                                <div className=' text-right'>
                                                    <button
                                                        type='submit'
                                                        className={clsx('inline-flex items-center px-4 py-2 font-semibold leading-6 text-sm shadow rounded-md text-white bg-indigo-500 hover:bg-indigo-400 transition ease-in-out duration-150 ', {
                                                            'cursor-not-allowed': loading,
                                                        })}
                                                        disabled={loading}
                                                    >
                                                        {loading && (
                                                            <svg
                                                                className='animate-spin -ml-1 mr-3 h-5 w-5 text-white'
                                                                xmlns='http://www.w3.org/2000/svg'
                                                                fill='none'
                                                                viewBox='0 0 24 24'
                                                            >
                                                                <circle
                                                                    className='opacity-25'
                                                                    cx='12'
                                                                    cy='12'
                                                                    r='10'
                                                                    stroke='currentColor'
                                                                    stroke-width='4'
                                                                ></circle>
                                                                <path
                                                                    className='opacity-75'
                                                                    fill='currentColor'
                                                                    d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
                                                                ></path>
                                                            </svg>
                                                        )}
                                                        开始上传
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                        <div className='modal-footer mt-3 text-right'></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
